package xq.gwt.ui.crud;

import xq.gwt.mvc.model.EntityModel;
import xq.gwt.mvc.model.PersistableEntityModel;
import xq.gwt.ui.rpc.AsyncCallbackAdapter;
import xq.gwt.ui.widgets.feedback.FeedbackService;

public class EntityListReaderImp implements EntityListReader{
	private EntityReceiver entityReceiver;
	private FilterModel filter;
	private PersistableEntityModel entity;
	protected OrderByModel orderBy[];
	

	@Override
	public void setEntityReceiver(EntityReceiver entityReceiver) {
		this.entityReceiver = entityReceiver;
	}

	@Override
	public void setFilter(FilterModel filter) {
		this.filter = filter;
		
	}

	@Override
	public void setOrderBy(OrderByModel[] orderBy){
		this.orderBy = orderBy;		
	}
	
	@Override
	public void setPrototypeEntity(PersistableEntityModel entity) {
		this.entity = entity;
		
	}

	@Override
	public void read() {
		CrudServiceProvider.persistanceService.fetch(entity,filter, orderBy,null,null, new EntitiesFetched());
		FeedbackService.getFeedbackPresenter().showFeedback("Зареждане на данни...");		
	}
	
	private void setEntities(EntityModel[] entities){
		if(entityReceiver!= null){
			entityReceiver.setEntities(entities);
		}
	}
	
	private class EntitiesFetched extends AsyncCallbackAdapter<FetchedEntities>{		
		@Override
		public void onSuccess(FetchedEntities result) {		
			setEntities(result.entities);
			FeedbackService.getFeedbackPresenter().showFeedback(null);
			if(result.entities != null){				
				if(result.outOfTotalEntities > result.entities.length){
					String feedback = "Само първите "+ result.entities.length +" от "+result.outOfTotalEntities+" записа са показани!";
					FeedbackService.getFeedbackPresenter().showFeedback(feedback);					
				}				
			}
			
		}	
	}
	
	
}
